//
//  MZdetailViewController.m
//  民族文化宫
//
//  Created by kobehjk on 14-8-3.
//  Copyright (c) 2014年 WANG CUNRUI. All rights reserved.
//

#import "MZdetailViewController.h"
static NSString *ID = @"MyCell";
@interface MZdetailViewController ()<UITableViewDataSource,UITableViewDelegate>


@property (strong, nonatomic) NSMutableArray *currentdata;
@property (nonatomic) NSInteger countp;
@property (strong,nonatomic) NSString *imagePath;
@end

@implementation MZdetailViewController


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.title = [NSString stringWithFormat:@"%@",_minzu];
    self.view = [[UIView alloc]initWithFrame:[UIScreen mainScreen].applicationFrame];
    //    self.edgesForExtendedLayout = UIRectEdgeNone;
    // 1. tableView
    CGRect frame = self.view.bounds;
    
    UITableView *moreView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height - 28) style:UITableViewStylePlain];
    // 1) 数据源
    [moreView setDataSource:self];
    // 2) 代理
    [moreView setDelegate:self];
    // 3) 设置表格高度
    //   [moreView setRowHeight:165];
    // 4) 设置分隔线
    [moreView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];

    
    [self.view addSubview:moreView];
    self.moreView = moreView;
    
    [self.moreView registerClass:[MZdetailTableViewCell class] forCellReuseIdentifier:ID];
    [self setupRefresh];
}

- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.moreView addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self.moreView headerBeginRefreshing];
    
#pragma mark 自动刷新(一进入程序就下拉刷新)
    
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.moreView addFooterWithTarget:self action:@selector(footerRereshing)];
}

#pragma mark - 加载JSON
- (void)headerRereshing
{
    NSString *urlString= [NSString stringWithFormat:@"http://210.30.0.167:6162/mzserver/Home/getcpinfoByMZ?minzu=%@&p=1",_minzu];
    
    
    NSString * encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes( kCFAllocatorDefault, (CFStringRef)urlString, NULL, NULL,  kCFStringEncodingUTF8 ));
    
    NSURL *urls =[NSURL URLWithString:encodedString];
    NSLog(@"%@",urls);
    
//    NSURL *urls = [NSURL URLWithString:[NSString stringWithFormat:@"http://210.30.0.167:6162/mzserver/Home/getcpinfoByMZ?minzu=%@&p=1",_minzu]];
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:urls];
    //request.delegate = self;
    [request startSynchronous];
    NSLog(@"下载产品数据中");
    NSError *error = [request error];
    if (!error) {
        _currentdata = [[request responseData]JSONValue] ;
        [self.moreView reloadData];
    }
    // 给数据列表赋值
    // 2.1.5秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.moreView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.moreView headerEndRefreshing];
    });
    _countp = 1;
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    NSLog(@"成功");
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
    UIAlertView *result = [[UIAlertView alloc] initWithTitle:@"提示" message:@"下载失败" delegate:self cancelButtonTitle:@"是" otherButtonTitles:@"否", nil];
    [result show];
    NSLog(@"失败");
}



- (void)footerRereshing
{
    
    NSLog(@"countp = %ld",(long)_countp);
    _countp = _countp + 1;
    NSLog(@"countp = %ld",(long)_countp);
    if ((_currentdata != nil)) {
        [self startRefresh:_countp];
        NSLog(@"countp = %ld",(long)_countp);
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 刷新表格
            [self.moreView reloadData];
            
            // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
            [self.moreView footerEndRefreshing];
        });
    }
    
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.moreView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.moreView footerEndRefreshing];
    });
}



#pragma mark - 注册单元格

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 225;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_currentdata count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 1. 使用可重用标示符查询可重用单元格
    MZdetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    NSDictionary *dic = _currentdata[indexPath.row];
    cell.textLabel.text = [dic objectForKey:@"cp_name"];
    NSString *s = [NSString stringWithFormat:@"(%@  %@)",[dic objectForKey:@"cp_shidai"],[dic objectForKey:@"cp_minzu"]];
    cell.label.text = s;
        NSLog(@"=%@",cell.label.text);
    NSString *pic = [dic objectForKey:@"cp_wenwutu"];

    NSRange foundObj = [pic rangeOfString :@";" options:NSCaseInsensitiveSearch];
    if(foundObj.length>0)
    {
        NSRange range = [pic rangeOfString:@";"];
        NSString *b = [pic substringToIndex:range.location];
        NSLog(@"b = %@",b);
        NSString *imagePath = [NSString stringWithFormat:@"http://www.mzdigital.cn/%@", b];
        NSLog(@"imagepath = %@",imagePath);
        _imagePath = imagePath;
    }else
    {
        NSString *imagePath = [NSString stringWithFormat:@"http://www.mzdigital.cn/%@", pic];
        //        NSURL *imageUrl = [NSURL URLWithString:imagePath];
        NSLog(@"%@",imagePath);
        _imagePath = imagePath;
    }
    //检测地址是否含有两张图片，有则取分号前一张
    [cell.imageview setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",_imagePath]] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
    NSLog(@"_imagepath = %@",_imagePath);
    
    
    return cell;
}


- (void)startRefresh:(NSInteger)count
{
    NSString *urlString= [NSString stringWithFormat:@"http://210.30.0.167:6162/mzserver/Home/getcpinfoByMZ?minzu=%@&p=%d",_minzu,_countp];
    
    
    NSString * encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes( kCFAllocatorDefault, (CFStringRef)urlString, NULL, NULL,  kCFStringEncodingUTF8 ));
    
    NSURL *url =[NSURL URLWithString:encodedString];
    
//    NSString *str = [NSString stringWithFormat:@"http://210.30.0.167:6162/mzserver/Home/getcpinfoByMZ?minzu=%@&p=&%ld",_minzu,(long)count];
    
//    NSURL *url = [NSURL URLWithString:str];
    NSLog(@"url2 = %@",url);
    // 2. 建立NSURLRequest
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:url];
    [request startSynchronous];
    NSLog(@"current2 = %lu",(unsigned long)_currentdata.count);
    NSLog(@"下载产品数据中");
    NSError *error = [request error];
    if (!error) {
        NSData *data = [request responseData];
//        NSLog(@"data2=%@",data.JSONValue );
        NSMutableArray *ARRAY = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSMutableArray *currentarray = [[NSMutableArray alloc]init];
        [currentarray addObjectsFromArray:_currentdata];
        [currentarray addObjectsFromArray:ARRAY];
        _currentdata = currentarray;
//        NSLog(@"array = %@",ARRAY);
        NSLog(@"current2.1 = %lu",(unsigned long)_currentdata.count);
        // 刷新表格
        [self.moreView reloadData];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    _moreViewController = [[MZdetailmoreViewController alloc] init];

    NSDictionary *dic = _currentdata[indexPath.row];
    _moreViewController.leibie = [dic objectForKey:@"cp_leibie"];
    _moreViewController.minzu = [dic objectForKey:@"cp_minzu"];
    _moreViewController.pic = [dic objectForKey:@"cp_wenwutu"];
    _moreViewController.time = [dic objectForKey:@"cp_shidai"];
    _moreViewController.content_c = [dic objectForKey:@"cp_shuoming"];
    _moreViewController.content_e = [dic objectForKey:@"TITLE"];
    _moreViewController.chicun = [dic objectForKey:@"cp_chicun"];
    _moreViewController.diqu = [dic objectForKey:@"cp_diqu"];
    _moreViewController.zhidi = [dic objectForKey:@"cp_zhidi"];;
    _moreViewController.name = [dic objectForKey:@"cp_name"];
    
    [self.navigationController pushViewController:_moreViewController animated:YES];
    
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
